<template>
  <div class="admin-medical-container">
    <div class="header">
      <h2>健康档案管理</h2>
      <el-button type="primary" @click="handleAdd">新增健康记录</el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="老人姓名">
          <el-input
            v-model="queryParams.elderName"
            placeholder="请输入老人姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="护工姓名">
          <el-input
            v-model="queryParams.caregiverName"
            placeholder="请输入护工姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="记录类型">
          <el-select
            v-model="queryParams.recordType"
            placeholder="请选择记录类型"
            clearable
            style="width: 200px"
          >
            <el-option label="血压" value="血压" />
            <el-option label="血糖" value="血糖" />
            <el-option label="体温" value="体温" />
            <el-option label="心率" value="心率" />
            <el-option label="体检" value="体检" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="elderName" label="老人姓名" width="120" align="center" />
        <el-table-column prop="caregiverName" label="记录护工" width="120" align="center" />
        <el-table-column prop="recordType" label="记录类型" width="100" align="center" />
        <el-table-column prop="recordValue" label="记录数值" width="120" align="center" />
        <el-table-column prop="recordUnit" label="单位" width="80" align="center" />
        <el-table-column prop="recordTime" label="记录时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.recordTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="详细描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="suggestions" label="建议措施" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleStatus(row)">
              {{ row.status === 'active' ? '设为失效' : '设为有效' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="老人" prop="elderId">
          <el-select
            v-model="formData.elderId"
            placeholder="请选择老人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="elder in elderList"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="记录类型" prop="recordType">
          <el-select
            v-model="formData.recordType"
            placeholder="请选择记录类型"
            style="width: 100%"
          >
            <el-option label="血压" value="血压" />
            <el-option label="血糖" value="血糖" />
            <el-option label="体温" value="体温" />
            <el-option label="心率" value="心率" />
            <el-option label="体检" value="体检" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录数值" prop="recordValue">
          <el-input
            v-model="formData.recordValue"
            placeholder="请输入记录数值"
          />
        </el-form-item>
        <el-form-item label="单位" prop="recordUnit">
          <el-input
            v-model="formData.recordUnit"
            placeholder="请输入单位"
          />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
            v-model="formData.recordTime"
            type="datetime"
            placeholder="选择记录时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="详细描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入详细描述"
          />
        </el-form-item>
        <el-form-item label="建议措施" prop="suggestions">
          <el-input
            v-model="formData.suggestions"
            type="textarea"
            :rows="3"
            placeholder="请输入建议措施"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="有效" value="active" />
            <el-option label="失效" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMedicalList, addMedical, updateMedical, updateMedicalStatus } from '@/api/medical'
import { getElderList } from '@/api/elder'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const dialogTitle = ref('')
const tableData = ref([])
const total = ref(0)
const elderList = ref([])
const formRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  elderName: '',
  caregiverName: '',
  recordType: '',
  dateRange: []
})

// 表单数据
const formData = reactive({
  medicalId: null,
  elderId: '',
  recordType: '',
  recordValue: '',
  recordUnit: '',
  recordTime: '',
  description: '',
  suggestions: '',
  status: 'active'
})

// 表单验证规则
const rules = {
  elderId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  recordType: [{ required: true, message: '请选择记录类型', trigger: 'change' }],
  recordValue: [{ required: true, message: '请输入记录数值', trigger: 'blur' }],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }]
}

// 生命周期
onMounted(() => {
  loadData()
  loadElderList()
})

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const response = await getMedicalList(queryParams)
    tableData.value = response.data.list || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('加载健康档案失败:', error)
    ElMessage.error('加载健康档案失败')
  } finally {
    loading.value = false
  }
}

// 加载老人列表
const loadElderList = async () => {
  try {
    const response = await getElderList({ pageNum: 1, pageSize: 1000 })
    elderList.value = response.data.list || []
  } catch (error) {
    console.error('加载老人列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    elderName: '',
    caregiverName: '',
    recordType: '',
    dateRange: []
  })
  loadData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  loadData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增健康记录'
  dialogVisible.value = true
  resetForm()
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑健康记录'
  dialogVisible.value = true
  Object.assign(formData, {
    medicalId: row.medicalId,
    elderId: row.elderId,
    recordType: row.recordType,
    recordValue: row.recordValue,
    recordUnit: row.recordUnit,
    recordTime: row.recordTime,
    description: row.description,
    suggestions: row.suggestions,
    status: row.status
  })
}

// 状态切换
const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '设为失效' : '设为有效'}吗？`,
      '提示',
      {
        type: 'warning'
      }
    )
    
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    await updateMedicalStatus({
      medicalId: row.medicalId,
      status: newStatus
    })
    
    ElMessage.success('操作成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (formData.medicalId) {
      await updateMedical(formData)
      ElMessage.success('更新成功')
    } else {
      await addMedical(formData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    medicalId: null,
    elderId: '',
    recordType: '',
    recordValue: '',
    recordUnit: '',
    recordTime: '',
    description: '',
    suggestions: '',
    status: 'active'
  })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    inactive: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusTextMap = {
    active: '有效',
    inactive: '失效'
  }
  return statusTextMap[status] || status
}
</script>

<style scoped>
.admin-medical-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}
</style>
